package com.leo.base.db.aop;

import com.leo.base.db.DynamicDataSourceContextHolder;
import com.leo.base.db.ReflectionUtil;
import com.leo.base.db.annotation.ShardingDataSource;
import com.leo.base.db.router.rule.ShardingRule;
import com.leo.base.exception.CustomException;
import com.leo.base.util.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Slf4j
@Aspect
@Component
public class ShardingDataSourceAspect {

    private static final String ERROR = "ShardingDataSource annotation error!!!";

    @Pointcut("@annotation(com.leo.base.db.annotation.ShardingDataSource)")
    public void pointcut() {
        // 不做处理
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws CustomException {
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        String methodName = method.getName();
        log.info("Method [{}] ShardingDataSource begin to change datasource", methodName);
        ShardingDataSource annotation = method.getAnnotation(ShardingDataSource.class);
        if (null == annotation) {
            annotation = method.getDeclaringClass().getAnnotation(ShardingDataSource.class);
            if (null == annotation) {
                log.error("Method [{}] can not find ShardingDataSource annotation", methodName);
                throw new CustomException(ERROR);
            }
        }

        String tableName = annotation.tableName();
        if (StringUtils.isBlank(tableName)) {
            log.error("Method [{}] get tableName of Annotation ShardingDataSource is null", methodName);
            throw new CustomException(ERROR);
        }

        ShardingRule rule = (ShardingRule) SpringContextUtil.getBean(tableName);
        if (null == rule) {
            log.error("Method [{}] get bean of ShardingRule is null", methodName);
            throw new CustomException(ERROR);
        }

        // 获取路由字段
        String shardingField = rule.getShardingField();
        if (StringUtils.isBlank(shardingField)) {
            log.error("Method [{}] get shardingField of ShardingRule is null", methodName);
            throw new CustomException(ERROR);
        }
        // 获取入参名称
        String[] parameterNames = ((MethodSignature) joinPoint.getSignature()).getParameterNames();
        if (null == parameterNames || parameterNames.length == 0) {
            log.error("Method [{}] get parameterNames of ShardingRule is null", methodName);
            throw new CustomException(ERROR);
        }
        // 获取入参值
        Object[] args = joinPoint.getArgs();
        if (null == args || args.length == 0) {
            log.error("Method [{}] get args of ShardingRule is null", methodName);
            throw new CustomException(ERROR);
        }

        int parameterNamesLength = parameterNames.length;
        String shardingFieldValue = ReflectionUtil.getShardingFieldValue(parameterNamesLength, args, shardingField, parameterNames);

        if (StringUtils.isBlank(shardingFieldValue)) {
            log.error("Method [{}] get shardingFieldValue of ShardingRule is null", methodName);
            throw new CustomException(ERROR);
        }

        String dataSourceKey = rule.getDataSourceKey(shardingFieldValue);

        log.info("Method [{}] ShardingDataSource switching datasource to [{}]", methodName, dataSourceKey);
        DynamicDataSourceContextHolder.setDataSourceKey(dataSourceKey);
        try {
            return joinPoint.proceed();
        } catch (Throwable throwable) {
            log.error("Method [{}] ShardingDataSource execute error, reason [{}]", methodName, throwable.getMessage());
            throw new CustomException(throwable.getMessage());
        }
    }

    @After("pointcut()")
    public void after() {
        DynamicDataSourceContextHolder.clearDataSourceKey();
    }
}
